#!/usr/bin/python
#-*- coding:utf-8 -*-

# places_dialog.py
#
# Copyright (c) 2008 Marcelo Lira dos Santos
#
# Author: Marcelo Lira dos Santos <setanta@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

import pygtk
pygtk.require('2.0')
import gtk
import gtk.glade
import pango
from os.path import join

import data
import guisupport as gs
try:
    import config as cfg
except:
    import config_dev as cfg

(
PLACES_COL_ID,
PLACES_COL_NAME,
) = range(2)

class PlacesDialog:

    def __init__(self, wtree, store):
        self.store = store
        self.place = None

        self.dialog = wtree.get_widget('places_dialog')
        self.dialog.set_icon(cfg.APPICON)
        self.dialog.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                gtk.STOCK_OK, gtk.RESPONSE_OK)

        self.places_treeview = wtree.get_widget('places_treeview')
        self.places_model = self.init_places()

        self.map_viewport = wtree.get_widget('map_viewport')
        self.map_image = wtree.get_widget('map_image')
        self.map_pixbuf = gtk.gdk.pixbuf_new_from_file(join(cfg.PIXMAPSPATH,
                                                       'tagmar_mapa.png'))
        self.map_image.set_from_pixbuf(self.map_pixbuf)
        self.map_width = self.map_pixbuf.props.width
        self.map_height = self.map_pixbuf.props.height

        self.place_info_vp = wtree.get_widget('place_info_viewport')
        self.place_info_vp.modify_bg(gtk.STATE_NORMAL, gs.COLOR_WHITE)

        self.crest_image = wtree.get_widget('crest_image')
        self.crest_image.clear()

        self.quote_textview = wtree.get_widget('quote_textview')
        self.quote_textbuffer = self.init_quotes()

        wtree.signal_autoconnect(self)

    # Callbacks ---------------------------------------------------------------
    def on_places_dialog_delete_event(self, widget, event):
        self.dialog.hide()
        return True

    def on_places_treeview_cursor_changed(self, widget):
        path, column = self.places_treeview.get_cursor()
        piter = self.places_model.get_iter(path)
        self.update(piter)

    # Auxiliary Methods -------------------------------------------------------
    def init_places(self):
        model = gtk.ListStore(int, str)
        self.places_treeview.set_model(model)

        column = gtk.TreeViewColumn('Reino/Região', gtk.CellRendererText(),
                                    text=PLACES_COL_NAME)
        column.set_expand(True)
        column.set_sort_column_id(PLACES_COL_NAME)
        self.places_treeview.append_column(column)

        for place_id, name in self.store.get_places_parents():
            model.append([place_id, name])

        return model

    def init_quotes(self):
        textbuffer = gtk.TextBuffer()
        self.quote_textview.set_buffer(textbuffer)

        tags = textbuffer.get_tag_table()

        tag = gtk.TextTag('title')
        tag.set_property('pixels-below-lines', 4)
        tag.set_property('font', 'sans bold 18')
        tag.set_property('justification', gtk.JUSTIFY_LEFT)
        tags.add(tag)

        tag = gtk.TextTag('quote')
        tag.set_property('pixels-below-lines', 4)
        tag.set_property('font', 'sans 11')
        tag.set_property('style', pango.STYLE_ITALIC)
        tags.add(tag)

        tag = gtk.TextTag('author')
        tag.set_property('pixels-below-lines', 4)
        tag.set_property('font', 'sans 11')
        tag.set_property('justification', gtk.JUSTIFY_RIGHT)
        tags.add(tag)

        return textbuffer


    def update(self, piter):
        place_id = self.places_model[piter][PLACES_COL_ID]
        self.place = self.store.get_place(place_id)

        if self.place.crest is None:
            self.crest_image.hide()
        else:
            self.crest_image.show()
            self.crest_image.set_from_pixbuf(self.place.crest)

        self.quote_textbuffer.set_text('')
        self.quote_textbuffer.insert_with_tags_by_name(
                self.quote_textbuffer.get_end_iter(),
                '%s\n' % self.place.name, 'title'
        )
        if self.place.quote is not None:
            quote, author = self.place.quote
            self.quote_textbuffer.insert_with_tags_by_name(
                    self.quote_textbuffer.get_end_iter(),
                    '"%s"\n' % quote, 'quote'
            )
            self.quote_textbuffer.insert_with_tags_by_name(
                    self.quote_textbuffer.get_end_iter(),
                    author, 'author'
            )

        #self.goto_coord(100, 100)
        x, y = self.place.coord
        self.map_viewport.get_hadjustment().set_value(x)
        self.map_viewport.get_vadjustment().set_value(y)

    def goto_coord(self, x, y):
        width = self.map_viewport.allocation.width
        height = self.map_viewport.allocation.height
        a = x - int(width / 2)
        b = y - int(height / 2)
        max_horiz = self.map_width - width
        max_vert = self.map_height - height
        if a < 0:
            a = 0
        elif a > max_horiz:
            a = max_horiz
        if b < 0:
            b = 0
        elif b > max_vert:
            b = max_vert

        #if self.timeout:
        #    gobject.source_remove(self.timeout)

        #self.pointer = (x, y)
        #self.pointer_counter = 6

        self.map_viewport.get_hadjustment().set_value(a)
        self.map_viewport.get_vadjustment().set_value(b)

    def reset(self):
        self.set_place_id(-1)

    def get_place(self):
        return self.place

    def set_place_id(self, place_id):
        if place_id < 0:
            self.place = None
            selection = self.places_treeview.get_selection()
            selection.unselect_all()
            self.quote_textbuffer.set_text('')
            self.crest_image.hide()
        else:
            for row in self.places_model:
                if row[PLACES_COL_ID] == place_id:
                    self.places_treeview.set_cursor(row.path)
                    self.update(row.iter)
                    break

    def run(self):
        self.dialog.show()

